package com.tally.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tally.server.domain.Login;
import com.tally.server.domain.LoginExample;
import com.tally.server.dto.LoginDTO;
import com.tally.server.dto.LoginPageDTO;
import com.tally.server.dto.PageDTO;
import com.tally.server.mapper.LoginMapper;
import com.tally.server.utils.CopyUtil;
import com.tally.server.utils.DateUtil;
import com.tally.server.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

/**
 * @Author: sy
 * @Date: 2020/12/25 11:21
 * @Description:
 */
@Service
public class LoginService {
    @Autowired
    private LoginMapper loginMapper;

    public void insert(LoginDTO loginDTO){
        Login login = CopyUtil.copy(loginDTO,Login.class);
        login.setId(UUIDUtil.getShortUUID());
        login.setLoginTime(new Date());
        loginMapper.insert(login);
    }

    public void list(LoginPageDTO pageDTO){
        LocalDate now = LocalDate.now();
        now = now.minus(30, ChronoUnit.DAYS);
        Date date = DateUtil.localDate2Date(now);

        PageHelper.startPage(pageDTO.getPage(), pageDTO.getSize());
        LoginExample loginExample = new LoginExample();
        loginExample.createCriteria().andUserIdEqualTo(pageDTO.getUserId()).andLoginTimeGreaterThan(date);
        loginExample.setOrderByClause("login_time desc");
        List<Login> loginList = loginMapper.selectByExample(loginExample);
        PageInfo<Login> pageInfo = new PageInfo<>(loginList);
        pageDTO.setTotal(pageInfo.getTotal());
        List<LoginDTO> categoryDTOList = CopyUtil.copyList(loginList, LoginDTO.class);
        pageDTO.setList(categoryDTOList);
    }
}
